<template>
  <div class="publishMomentsContainer autoGrow flex-row">
    <div class="publishContent">
      <div class="subTitle">发布内容</div>
      <!-- <quick-replies
        title=""
        ref="quickReply"
        @add="changeContent"
        :btnsTop="true"
        :upToStore="false"
        :types="['text', 'link', 'image', 'video', 'documents']"
        textPlaceHolder="请输入发布的文字"
        :showReplies="false"></quick-replies> -->
        <div style="padding:0 10px">
           <messageButtonGroup 
            :csid="csid" 
            :types="['text','image','video','link','document']"
            @create="changeContent"
          />
        </div>
     
      <div class="drafts">
          <div class="textDraft" v-if="drafts[0]" v-html="emojiParse(drafts[0].content)">
          </div>
          <div class="change" v-if="drafts[0]">
            <!-- <span class="clickedSpan" @click="changeDraft(drafts[0])">修改</span> -->
          </div>
          <div class="oneImageDraft" v-if="drafts[1] && Array.isArray(drafts[1]) && drafts[1].length ==1">
            <div class="imgBox">
              <img :src="config.apiUrl+ '/'+ drafts[1][0].src" alt="">
              <!-- <img :src="drafts[1][0].src" alt=""> -->
              <i class="layui-icon layui-icon-delete" @click="deleteDraftImg(0)"></i>
            </div>
          </div>
          <div class="imagesDraft flex-row" v-if="drafts[1] && Array.isArray(drafts[1]) && drafts[1].length > 1">
            <div class="imgBox" v-for="(img, i) in drafts[1]" :key="i">
              <img :src="config.apiUrl+ '/' + img.src" alt="">
              <i class="layui-icon layui-icon-delete" @click="deleteDraftImg(i)"></i>
            </div>
          </div>
          <div class="linkDraft flex-column" v-if="drafts[1] && drafts[1].msgtype=='10'">
            <div class="linkTitle textEllipsis">{{drafts[1].title}}</div>
            <div class="flex-row linkDetail">
              <div class="linkDesc fontGrey">{{drafts[1].content}}</div>
              <img :src="drafts[1].src" alt="">
              <!-- <img :src="drafts[1].cover" alt=""> -->
            </div>
          </div>
          <div class="videoDraft" v-if="drafts[1] && drafts[1].msgtype=='4'">
            <video :src="config.apiUrl+ '/'+drafts[1].src" controls></video>
          </div>
          <div class="change" v-if="drafts[1] && !Array.isArray(drafts[1])">
            <!-- <span class="clickedSpan" @click="changeDraft(drafts[1])">修改</span> -->
          </div>
      </div>
       
      <div class="sendRequests flex-row" v-if="drafts.length">
        <button
          @click="sendNow()"
          class="layui-btn layui-btn-sm">
          即时发送
        </button>
        <button
          @click="setSendTime"
          class="layui-btn layui-btn-primary layui-btn-sm">
          定时发送
        </button>
      </div>
    </div>
    <div class="publishRecords autoGrow">
      <div class="subTitle">发布记录</div>
      <div class="momentsList flex-column autoGrow">
        <div class="momentsItem flex-column" :key="index" v-for="(moment, index) in moments">
          <div class="momentsItemAuthor flex-row">
            <img :src="accounts[moment.wxaccount]&&accounts[moment.wxaccount].avatar" alt="" class="avatar">
            <div class="autoGrow">
              <div class="authorName flex-row">
                <span style="color:#566a94">{{accounts[moment.wxaccount]&&accounts[moment.wxaccount].nick}}</span>
                <div class="buttons">
                <button class="layui-btn layui-btn-xs" v-if="moment.status === 0 ">待发布</button>
                <button class="layui-btn layui-btn-xs layui-btn-danger" v-if="moment.status === 0" @click="cancelSend(moment)">取消发送</button>
                <!-- <button class="layui-btn layui-btn-warm layui-btn-xs" v-if="moment.status === 1" @click="deleteMoment(moment)">删除</button> -->
              </div>
              </div>
              <div class="content-text" v-if="moment.msg">{{moment.msg}}</div>
            </div>
          </div>
          <div class="momentsResources flex-column">
            <div class="flex-row momentMedia">
              <div v-if="moment.msgtype==2 && moment.src[0]">
                
                <div class="images flex-row" v-if="moment.src.length==1">
                  <img :preview="moment.id" :src="config.apiUrl+'/'+img" alt="" v-for="(img, i) in moment.src" :key="i" style="width:200px">
                </div>
                <div class="images-grid" v-if="moment.src.length!=1">
                  <img :preview="moment.id" class="multi-image" v-for="(img, i) in moment.src" :key="i" :src="config.apiUrl+'/'+img" />
                </div>

              </div>
              
              <video-player
                v-if="moment.msgtype==4 && moment.src[0]"
                :src="config.apiUrl+'/'+moment.src[0]"
                width="200px"
              ></video-player>

              <a :href="moment.url" target="_blank" class="linkDraft flex-column" v-if="moment.msgtype==10">
                <img class="news-image" :src="moment.src[0]" alt="">
                <div class="flex-row linkDetail">
                  <div class="linkDesc fontGrey">{{moment.title||moment.content}}</div>
                </div>
              </a>

              
            </div>
            <div class="sendTime fontGrey">
              {{moment.addType==1 ? '定时发布：' : '发布时间：'}} {{moment.time}}
            </div>
          </div>
        </div>
      </div>
    </div>
    <time-picker
      v-if="showDatePicker"
      @closeTimePicker="()=>this.showDatePicker=false"
      @submit="submitSendTime">
    </time-picker>
  </div>
</template>
<script>
import VideoPlayer from '@/components/videoPlayer'
import QuickReplies from './quickReplies'
import TimePicker from '@/components/timePicker';
import { mapState } from 'vuex';
import messageButtonGroup from '@/components/message-button-group'
import emojiParse from '@/lib/wechat-emoji'

export default {
  name: 'publishMonents',
  data() {
    return {
      showDatePicker: false,
      moments: [],
      drafts: [],
      accounts:{}
    }
  },
  props:{
    currentService:{}
  },
  created(){
    this.services = this.currentService
    
  },
  computed:{
    ...mapState(['uistate','accountMap']),
    csid(){
      return this.uistate.adminid
    }
  },

  mounted() {
    this.getMoments()
    const accountMap = this.accountMap

    if(accountMap){
      let accounts = {}
      Object.values(accountMap).forEach(account=>{
        accounts[account.wxid] = account
      })
      this.accounts = accounts
    }
  },
  components: {
    VideoPlayer,
    QuickReplies,
    TimePicker,
    messageButtonGroup
  },
  watch:{
    currentService(newservice,oldservice){ 
      this.services = this.currentService
    },
    accountMap(newval,oldval){
      if(newval){
        let accounts = {}
        Object.values(newval).forEach(account=>{
          accounts[account.wxid] = account
        })
        this.accounts = accounts
      }
    }
  },
  methods: {
    emojiParse,
    cancelSend(moment) {
      this.deleteMoment(moment)
    },
    deleteMoment(moment) {
      this.$api.timeline.cancelTimeline({id:moment.id})
        .then(data=>{
          this.moments = this.moments.filter(m=>m.id!==moment.id)
          console.log(data)
        })
        .catch(console.log)
    },
    changeContent(data) {
      if (data.msgtype == 1) {
        this.$set(this.drafts, 0, data)
      } else if (data.msgtype == 2) {
        let images = this.drafts[1]
        
        if (Array.isArray(images) && images.length < 9) {
          images.push(data)
        } else if (Array.isArray(images) && images.length == 9) {
          return this.$msg('最多发布9张图片')
        } else {
          images = [data]
        }
        this.$set(this.drafts, 1, images)
      } else if(typeof data.msgtype !== 'undefined'){
        this.$set(this.drafts, 1, data)
      }
    },
    sendNow(time) {
      if(!this.services || !this.services.length)return this.$msg('请选择账号')
      if(!this.drafts || !this.drafts.length)return this.$msg('请填写发布内容')
      const { csid,wxid } = this.services[0]
      const wxAccounts = this.services.map(item=>item.wxid)
      const [text,att] = this.drafts
      let msgtype = 1,src,msg,title,content,url;
      if(text){
        msg = text?text.content:''
      }
      if(att instanceof Array){
        msgtype = 2
        src = att.map(item=>item.src)
      }else if(att){
        msgtype = att.msgtype
        if(msgtype === 4 ){
          src = [att.src]
        }else{
          msgtype = 10
          title = att.title
          url = att.url
          content = att.content
          src = [att.src]
        }
      }
      
      const timelineContent = {
          msgtype, //图片 视频 链接
          src, //链接的缩略图或图片地址， 组
          msg,//:"文字内容",
          //以下是卡片内容
          title,//:"",//链接标是
          content,//":"",//链接描述
          url,//:""//链接地址
      }

      const params = {
         wxAccount:wxAccounts ,//发送帐号， 
         csId:csid , //客服ID, 
         timelineContent:JSON.stringify(timelineContent) ,//发送内容，
         sendType: time?1:0,//0即时，1定时，
         sendtime: time,//定时发送时间
      }
      this.$api.timeline.createTimeline(params)
        .then(data=>{
          this.$msg('任务创建成功')
          try{
            this.moments = [...data.map(item=>this.transToMoment(item)),...this.moments]
            this.drafts = []
          }catch(e){
            console.log(e)
          }
          
          console.log(data)
        })
        .catch(e=>this.$msg(e))
    },
    setSendTime() {
      this.showDatePicker = true
    },
    submitSendTime(time) {
      this.showDatePicker = false;
      this.sendNow(time)
    },
    changeDraft(draft) {
      if (!Array.isArray(draft)) {
        this.$refs.quickReply.showQuickReplyDialog(draft.type)
        this.$refs.quickReply.setDialogData(draft)
      }
    },
    deleteDraftImg(index) {
      this.drafts[1].splice(index, 1)
    },
    getAccountByWxid(wxid){
      let account = {}
      Object.values(this.accountMap)
        .forEach(_account=>{
          
          if(_account.wxid == item.wxaccount ){
            account = _account
          }
        })
      return account  
    },
    transToMoment(item){
      const content = JSON.parse(item.timelinecontent)
      const _item = {
        ...content,
        type: item.status,
        time: this.formatTime(item.sendtime||new Date()),
        ...item
      }
      return _item
    },

    getMoments(){
      const csid = this.uistate.adminid
      const params = {
         csId:csid, pageSize:20, pageNo:1
      }
      this.$api.timeline.getTimelines(params)  
        .then(data=>{
          this.moments = data.map(item=>this.transToMoment(item))
        })
        .catch(e=>this.$msg(e))
    }
    
  }
}
</script>
<style scoped>

.momentsList{
  height: 100%;
  overflow: auto
}
.momentsContainer .momentsItem{
  margin-bottom: 0
}
.momentsResources .linkDraft{
  background: #f4f3f8;
  padding: 6px;
  display: flex;
  flex-direction: row;
  width: 450px;
  border-radius: 5px;
}
.momentsResources .linkDraft .linkDetail{
  padding: 5px 0 5px 5px;
  box-sizing: border-box;
  
}
.momentsResources .linkDraft .linkDesc{
   text-overflow: -o-ellipsis-lastline;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;

  line-height: 16px;
  font-size: 14px;
  color: #333
}
.momentsResources .linkDraft .news-image{
  width: 40px;
  height: 40px;
  border-radius: 2px;
  flex-shrink: 0
}
.momentsItem .content-text{
  width:450px;
  line-height: 18px;
}
.momentsItem .avatar{
  border-radius: 3px;
  background-color: #ccc;
}
.momentsResources .sendTime{
  color: #b2b2b2;
  font-size: 14px
}
.momentsResources .images-grid{
  display: grid;
  grid-template-columns: 80px 80px 80px;
  grid-row-gap: 5px;
  grid-column-gap: 5px;
}
.momentsResources .multi-image{
  width: 80px;
  height: 80px; 
  object-fit: cover;
  border-radius: 3px;
}
</style>
